import { authenticateToken } from "../../../lib/auth.js";
import { getConnection } from "../../../lib/db.js";
import { validateLookupItem } from "../../../lib/validation.js";

const handler = async function handler(req, res) {
  try {
    const user = req.user;
    const { id } = req.query;
    const connection = await getConnection();

    // 验证字典项是否存在且属于当前租户
    const [itemResult] = await connection.execute(
      `SELECT li.*, lt.name as type_name, lt.code as type_code, lt.is_system as type_is_system
       FROM lookup_items li
       LEFT JOIN lookup_types lt ON li.type_id = lt.id
       WHERE li.id = ? AND li.tenant_id = ?`,
      [id, user.tenant_id]
    );

    if (itemResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: "字典项不存在",
      });
    }

    const lookupItem = {
      ...itemResult[0],
      extra_data: itemResult[0].extra_data
        ? JSON.parse(itemResult[0].extra_data)
        : null,
    };

    if (req.method === "GET") {
      // 获取字典项详情，包含子级项目
      const [childrenResult] = await connection.execute(
        "SELECT * FROM lookup_items WHERE parent_id = ? AND tenant_id = ? ORDER BY sort_order ASC",
        [id, user.tenant_id]
      );

      const children = childrenResult.map((child) => ({
        ...child,
        extra_data: child.extra_data ? JSON.parse(child.extra_data) : null,
      }));

      res.status(200).json({
        success: true,
        data: {
          ...lookupItem,
          children,
        },
      });
    } else if (req.method === "PUT") {
      // 更新字典项
      if (user.role !== "administrator" && user.role !== "operator") {
        return res.status(403).json({
          success: false,
          message: "权限不足，需要管理员或操作员权限",
        });
      }

      // 系统预置项不允许修改代码和名称
      if (
        lookupItem.is_system &&
        (req.body.code !== lookupItem.code || req.body.name !== lookupItem.name)
      ) {
        return res.status(400).json({
          success: false,
          message: "系统预置字典项不允许修改代码和名称",
        });
      }

      const validation = validateLookupItem(req.body);
      if (!validation.success) {
        return res.status(400).json({
          success: false,
          message: validation.message,
          errors: validation.errors,
        });
      }

      const {
        parent_id,
        code,
        name,
        value,
        description,
        extra_data,
        sort_order,
        status,
      } = req.body;

      // 如果修改了代码，检查是否重复
      if (code !== lookupItem.code) {
        const [existingItem] = await connection.execute(
          "SELECT id FROM lookup_items WHERE tenant_id = ? AND type_id = ? AND code = ? AND id != ?",
          [user.tenant_id, lookupItem.type_id, code, id]
        );

        if (existingItem.length > 0) {
          return res.status(400).json({
            success: false,
            message: "字典项代码在该类型下已存在",
          });
        }
      }

      // 处理层级关系变更
      let level = lookupItem.level;
      if (parent_id !== lookupItem.parent_id) {
        if (parent_id) {
          // 检查新的父级是否有效
          const [parentResult] = await connection.execute(
            "SELECT level FROM lookup_items WHERE id = ? AND tenant_id = ? AND type_id = ?",
            [parent_id, user.tenant_id, lookupItem.type_id]
          );

          if (parentResult.length === 0) {
            return res.status(400).json({
              success: false,
              message: "父级字典项不存在",
            });
          }

          // 检查不能设置自己或自己的子级作为父级
          const [circularCheck] = await connection.execute(
            `WITH RECURSIVE item_tree AS (
              SELECT id, parent_id FROM lookup_items WHERE id = ?
              UNION ALL
              SELECT li.id, li.parent_id 
              FROM lookup_items li
              INNER JOIN item_tree it ON li.parent_id = it.id
            )
            SELECT COUNT(*) as count FROM item_tree WHERE id = ?`,
            [id, parent_id]
          );

          if (circularCheck[0].count > 0) {
            return res.status(400).json({
              success: false,
              message: "不能设置自己或子级作为父级",
            });
          }

          level = parentResult[0].level + 1;
        } else {
          level = 1;
        }
      }

      const updateQuery = `
        UPDATE lookup_items 
        SET parent_id = ?, code = ?, name = ?, value = ?, description = ?, 
            extra_data = ?, level = ?, sort_order = ?, status = ?, updated_at = NOW()
        WHERE id = ? AND tenant_id = ?
      `;

      await connection.execute(updateQuery, [
        parent_id || null,
        code,
        name,
        value || "",
        description || "",
        extra_data ? JSON.stringify(extra_data) : null,
        level,
        sort_order || 0,
        status !== undefined ? status : 1,
        id,
        user.tenant_id,
      ]);

      // 如果层级发生变更，需要更新所有子级的层级
      if (level !== lookupItem.level) {
        const levelDiff = level - lookupItem.level;
        await connection.execute(
          `UPDATE lookup_items 
           SET level = level + ?, updated_at = NOW()
           WHERE tenant_id = ? AND id IN (
             WITH RECURSIVE item_tree AS (
               SELECT id FROM lookup_items WHERE parent_id = ?
               UNION ALL
               SELECT li.id 
               FROM lookup_items li
               INNER JOIN item_tree it ON li.parent_id = it.id
             )
             SELECT id FROM item_tree
           )`,
          [levelDiff, user.tenant_id, id]
        );
      }

      res.status(200).json({
        success: true,
        message: "字典项更新成功",
      });
    } else if (req.method === "DELETE") {
      // 删除字典项
      if (user.role !== "administrator") {
        return res.status(403).json({
          success: false,
          message: "权限不足，只有管理员才能删除字典项",
        });
      }

      // 系统预置项不允许删除
      if (lookupItem.is_system) {
        return res.status(400).json({
          success: false,
          message: "系统预置字典项不允许删除",
        });
      }

      // 检查是否有子级项
      const [childCount] = await connection.execute(
        "SELECT COUNT(*) as count FROM lookup_items WHERE parent_id = ? AND tenant_id = ?",
        [id, user.tenant_id]
      );

      if (childCount[0].count > 0) {
        return res.status(400).json({
          success: false,
          message: `无法删除，该字典项下还有 ${childCount[0].count} 个子项`,
        });
      }

      await connection.execute(
        "DELETE FROM lookup_items WHERE id = ? AND tenant_id = ?",
        [id, user.tenant_id]
      );

      res.status(200).json({
        success: true,
        message: "字典项删除成功",
      });
    } else {
      res.status(405).json({
        success: false,
        message: "不支持的请求方法",
      });
    }
  } catch (error) {
    console.error("Lookup item API error:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

export default authenticateToken(handler);
